package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.AttendanceRecord;
import org.example.models.R;
import org.example.service.AttendanceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @Author: 鸢一折纸
 * @Email: 3498881048@qq.com
 * @Date: 2025/09/04 10:00
 * @Description:
 **/

@RestController
@RequestMapping("/attendanceRecord")
public class AttendanceRecordController {

    @Autowired
    private AttendanceRecordService attendanceRecordService;

    @GetMapping("/page")
    public R<Page<AttendanceRecord>> getAllAttendanceRecord(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "4") int size,
            @RequestParam(name = "userId", required = false) Integer userId,
            @RequestParam(name = "attendanceCycle", required = false) String attendanceCycle,
            @RequestParam(name = "startDate", required = false) String startDate
    ) {
        QueryWrapper<AttendanceRecord> query = new QueryWrapper<>();
        query.lambda().eq(AttendanceRecord::getUserId, userId);
        if (attendanceCycle != null && !attendanceCycle.isEmpty()) {
            query.lambda().like(AttendanceRecord::getAttendanceCycle, attendanceCycle);
            query.lambda().le(AttendanceRecord::getRecordDate, new Date());
        } else {
            //获取当前年份-月份
            LocalDate now = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String yearMonth = now.format(formatter);
            query.lambda().like(AttendanceRecord::getAttendanceCycle, yearMonth);
        }

        if (startDate != null && !startDate.isEmpty()) {
//            query.lambda().between(AttendanceRecord::getRecordDate, startDate, new Date());
            query.lambda().eq(AttendanceRecord::getRecordDate, startDate);
        }

        query.lambda().le(AttendanceRecord::getRecordDate, new Date());
        query.lambda().orderByDesc(AttendanceRecord::getRecordDate);

        Page<AttendanceRecord> page = new Page<>(current, size);
        attendanceRecordService.page(page, query);
        return R.success(page);
    }

    @GetMapping("/statisticsAttendanceCycle")
    public R<List<String>> statisticsAttendanceCycle() {
        List<String> list = attendanceRecordService.statisticsAttendanceCycle();
        return R.success(list);
    }

    @GetMapping("findByRecordDate")
    public R<AttendanceRecord> findByRecordDate(@RequestParam("recordDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date recordDate,
                                                @RequestParam(name = "userId", required = false) Integer userId) {
        QueryWrapper<AttendanceRecord> query = new QueryWrapper<>();
        query.lambda().eq(AttendanceRecord::getUserId, userId);
        query.lambda().eq(AttendanceRecord::getRecordDate, recordDate);
        AttendanceRecord attendanceRecord = attendanceRecordService.getOne(query);

        if (attendanceRecord == null) {
            return R.error("未找到该日期的考勤记录");
        }

        return R.success(attendanceRecord);
    }

    @PostMapping("/clockIn")
    public R<String> clockIn(@RequestParam("recordDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date recordDate,
                             @RequestParam("attendanceCycle") String attendanceCycle,
                             @RequestParam("clockInTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date clockInTime,
                             @RequestParam("clockInStatus") String clockInStatus,
                             @RequestParam("lateMinutes") Integer lateMinutes,
                             @RequestParam("earlyMinutes") Integer earlyMinutes,
                             @RequestParam("locationStatus") String locationStatus,
                             @RequestAttribute("userId") Integer userId) {

        // 获取当天的考勤记录
        R<AttendanceRecord> result = findByRecordDate(recordDate, userId);
        AttendanceRecord existingRecord = result.getData();

        // 转换为LocalDateTime
        LocalDateTime localDateTime = clockInTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        // 判断是上午还是下午
        boolean isMorning = localDateTime.getHour() < 12;

        // 检查是否已经签到
        boolean alreadyCheckedIn = false;
        if (existingRecord != null) {
            if (isMorning && existingRecord.getMorningStatus() != null &&
                    !"未签到".equals(existingRecord.getMorningStatus().toString())) {
                alreadyCheckedIn = true;
            } else if (!isMorning && existingRecord.getAfternoonStatus() != null &&
                    !"未签到".equals(existingRecord.getAfternoonStatus().toString())) {
                alreadyCheckedIn = true;
            }
        }

        // 如果已经签到，则不允许重复打卡
        if (alreadyCheckedIn) {
            return R.error("该时间段已不可打卡，请查看考勤记录");
        }

        // 设置打卡信息
        if (isMorning) {
            // 上午打卡
            existingRecord.setMorningClock(clockInTime);
            existingRecord.setMorningStatus(clockInStatus);
            existingRecord.setLateMinutes(lateMinutes);
        } else {
            // 下午打卡
            existingRecord.setAfternoonClock(clockInTime);
            existingRecord.setAfternoonStatus(clockInStatus);
            existingRecord.setEarlyLeaveMinutes(earlyMinutes);
        }

        existingRecord.setLocation(locationStatus);

        // 保存记录
        boolean b = attendanceRecordService.updateById(existingRecord);

        return b ? R.success("打卡成功,考勤状态已更新") : R.error("打卡失败");
    }


}
